package gui.impianto;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import common.ResultSetTableModel;

import core.Message;

import db.CustomerDBInteraction;
import db.DBConnection;
import db.ImpiantoDBInteraction;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ShowListaImpiantiJPanel extends javax.swing.JPanel {

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private JPanel headerjPanel;
	private JScrollPane jScrollPane1;
	private JButton chiudijButton;
	private JButton aggiungiImpiantojButton;
	private JButton dettaglijButton;
	private JPanel pulsantijPanel;
	private JTable impiantijTable;
	private JPanel tablejPanel;
	private JLabel comunejLabel;
	private JLabel logojLabel;
	private JLabel indirizzojLabel;
	private JLabel cognomejLabel;
	private JPanel infoClientejPanel;
	
	/**
	 * Private field given into new constructor
	 */
	private String codiceCliente;
	
	/**
	 * the container frame of JPanel
	 */
	private JInternalFrame thisFrame;

	private DBConnection dbCon;
	
	private JDesktopPane deskPane;
	
	private ShowListaImpiantiJPanel showListaImpianti;
	
	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		try {
			frame.getContentPane().add(new ShowListaImpiantiJPanel("1", new JInternalFrame(), new DBConnection()));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public ShowListaImpiantiJPanel() {
		super();
		initGUI();
	}
	
	
	/**
	 * Constructor which takes customer's code and set into a private field 
	 * @param codice
	 */
	public ShowListaImpiantiJPanel(String codice, JInternalFrame thisFrame, DBConnection dbCon, JDesktopPane deskPane) {
		super();
		this.thisFrame = thisFrame;
		this.codiceCliente = codice;
		this.dbCon = dbCon;
		this.deskPane = deskPane;
		this.showListaImpianti = this;
		initGUI();
		this.getInfoFromDB();
	}
	
	/**
	 * Constructor which takes customer's code and set into a private field 
	 * @param codice
	 */
	public ShowListaImpiantiJPanel(String codice, JInternalFrame thisFrame, DBConnection dbCon) {
		super();
		this.thisFrame = thisFrame;
		this.codiceCliente = codice;
		this.dbCon = dbCon;
		initGUI();
		this.getInfoFromDB();
	}
	
	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(484, 329));
			{
				headerjPanel = new JPanel();
				GridBagLayout headerjPanelLayout = new GridBagLayout();
				this.add(headerjPanel);
				headerjPanel.setPreferredSize(new java.awt.Dimension(465, 150));
				headerjPanelLayout.rowWeights = new double[] {0.1};
				headerjPanelLayout.rowHeights = new int[] {7};
				headerjPanelLayout.columnWeights = new double[] {0.1, 0.1};
				headerjPanelLayout.columnWidths = new int[] {7, 7};
				headerjPanel.setLayout(headerjPanelLayout);
				{
					infoClientejPanel = new JPanel();
					GridBagLayout infoClientejPanelLayout = new GridBagLayout();
					infoClientejPanelLayout.rowWeights = new double[] {0.1, 0.1, 0.1, 0.1};
					infoClientejPanelLayout.rowHeights = new int[] {7, 7, 7, 7};
					infoClientejPanelLayout.columnWeights = new double[] {0.1};
					infoClientejPanelLayout.columnWidths = new int[] {7};
					infoClientejPanel.setLayout(infoClientejPanelLayout);
					headerjPanel.add(infoClientejPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
					infoClientejPanel.setBorder(BorderFactory.createTitledBorder("Info Cliente"));
					{
						cognomejLabel = new JLabel();
						infoClientejPanel.add(cognomejLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
						cognomejLabel.setText("Cognome Nome (ID)");
						cognomejLabel.setFont(new java.awt.Font("Segoe UI",3,12));
					}
					{
						indirizzojLabel = new JLabel();
						infoClientejPanel.add(indirizzojLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
						indirizzojLabel.setText("Via Indirizzo Nuovo, numero");
						indirizzojLabel.setFont(new java.awt.Font("Segoe UI",3,12));
					}
					{
						comunejLabel = new JLabel();
						infoClientejPanel.add(comunejLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
						comunejLabel.setText("Comune (PROV)");
						comunejLabel.setFont(new java.awt.Font("Segoe UI",3,12));
					}
				}
				{
					logojLabel = new JLabel();
					headerjPanel.add(logojLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					logojLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/icons/lista128.png")));
				}
			}
			{
				tablejPanel = new JPanel();
				this.add(tablejPanel);
				tablejPanel.setPreferredSize(new java.awt.Dimension(467, 103));
				tablejPanel.setBorder(BorderFactory.createTitledBorder("Lista Impianti"));
				{
					jScrollPane1 = new JScrollPane();
					tablejPanel.add(jScrollPane1);
					jScrollPane1.setPreferredSize(new java.awt.Dimension(451, 69));
					{

						impiantijTable = new JTable();
						jScrollPane1.setViewportView(impiantijTable);
						TableModel tableModel = getTableModel();
						setModel(tableModel);
						impiantijTable.setAutoCreateRowSorter(true);
					}
				}
			}
			{
				pulsantijPanel = new JPanel();
				this.add(pulsantijPanel);
				pulsantijPanel.setPreferredSize(new java.awt.Dimension(445, 46));
				{
					dettaglijButton = new JButton();
					pulsantijPanel.add(dettaglijButton);
					dettaglijButton.setText("Visualizza Dettagli");
					dettaglijButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/icons/detail32.png")));
					dettaglijButton.setToolTipText("Visualizza dettagli impianto selezionato");
					dettaglijButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent e) {
							String codiceImpianto = impiantijTable.getValueAt(impiantijTable.getSelectedRow(), 0).toString();
							JInternalFrame intFrame = new JInternalFrame("Visualizza dettagli impianto cod. " + codiceImpianto);
							intFrame.getContentPane().add(new ShowImpiantoJPanel(codiceImpianto, thisFrame, dbCon, deskPane));
							setInternalFrameProperties(intFrame, true);
						}
					});
				}
				{
					aggiungiImpiantojButton = new JButton();
					pulsantijPanel.add(aggiungiImpiantojButton);
					aggiungiImpiantojButton.setText("Aggiungi Impianto");
					aggiungiImpiantojButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/icons/add32.png")));
					aggiungiImpiantojButton.setToolTipText("Aggiungi Nuovo Impianto");
					aggiungiImpiantojButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent e) {
							JInternalFrame intFrame = new JInternalFrame("Inserisci Nuovo Impianto", false);
							intFrame.getContentPane().add(new JScrollPane(new NuovoImpiantoJPanel(deskPane, codiceCliente, dbCon, intFrame, showListaImpianti)));
							setInternalFrameProperties(intFrame, true);
						}
					});
					
				}
				{
					chiudijButton = new JButton();
					pulsantijPanel.add(chiudijButton);
					chiudijButton.setText("Chiudi Finestra");
					chiudijButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/icons/close32.png")));
					chiudijButton.setToolTipText("Chiudi la finestra corrente");
					chiudijButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							closeWindow();
						}
					});
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * This function allows to get info from DB
	 */
	private void getInfoFromDB()
	{
	
		try {
			ResultSet res = CustomerDBInteraction.getCustomerInfo(codiceCliente, dbCon);
			res.next();
			String temp = res.getString("Cognome") + " " + res.getString("Nome") + " (id=" + this.codiceCliente + ")";
			this.cognomejLabel.setText(temp);
			this.indirizzojLabel.setText(res.getString("Indirizzo"));
			this.comunejLabel.setText(res.getString("CAP") + " - " + res.getString("ComuneDiResidenza").toUpperCase());
			// TODO prendere tutti gli impianti collegati al cliente e inserirli nella tabella.
			
		} catch (SQLException e) {
			// TODO Delete printStackTrace()
			e.printStackTrace();
			Message.errorMessage("Errore nel caricamento dei dati! Riprovare", "Errore caricamento dati");
		}
		
	}
	
	/**
	 * This function allows to close window
	 */
	private void closeWindow() {
		this.thisFrame.dispose();
	}
	
	/**
	 * This function allows to get the ResultSetTableModel of "impianti" from database
	 * @return
	 */
	private TableModel getTableModel()
	{
		ResultSetTableModel rstm = new ResultSetTableModel(ImpiantoDBInteraction.getImpiantiOfCustomerForTable(codiceCliente, dbCon));
		return rstm;	
	}
	
	/**
	 * This function sets the model of the table, personalizing the names of the columns and other stuff
	 * @param tableModel - the current tableModel
	 */
	private void setModel(TableModel tableModel)
	{
		impiantijTable.setModel(tableModel);
		TableColumnModel cm = impiantijTable.getColumnModel();
		TableColumn colonnaCodice = cm.getColumn(0);
		colonnaCodice.setMaxWidth(40);
		colonnaCodice.setHeaderValue("COD");
		TableColumn colonnaLocale = cm.getColumn(4);
		colonnaLocale.setHeaderValue("LOCALE");
		TableColumn colonnaStato = cm.getColumn(5);
		colonnaStato.setHeaderValue("STATO");
	}
	
	public void setInternalFrameProperties(JInternalFrame intFrame, boolean centered)
	{
		intFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		intFrame.pack();
		intFrame.moveToFront();
		intFrame.setVisible(true);
		deskPane.add(intFrame);
		// Very important function to set the frame on top
		deskPane.selectFrame(false);
		intFrame.setLocation(200, 0);
		intFrame.setClosable(true);
		intFrame.setIconifiable(true);
		// This instructions will center the jInternaFrame if we setted centered on true
		if(centered)
		{	
			intFrame.setLocation((deskPane.getSize().width - intFrame.getSize().width)/2,
			    (deskPane.getSize().height- intFrame.getSize().height)/2);
		}
	}

	/**
	 * This public function allows to refresh the JTable after a insert from NuovoImpiantoJPanel
	 */
	public void refreshJTableAfterANewInsert()
	{
		setModel(getTableModel());
	}
	

}
